/*
 * @Description: 利用权限上下文
 * @Author: Rfan
 * @Date: 2022-04-07 15:49:26
 * @LastEditTime: 2022-05-25 09:01:18
 */

import { createContext, useContext, useEffect, useReducer } from 'react';
import { message } from 'antd';
import { UseRightReducer } from '../reducers/UseRightReducer';
import { SAVE_FORM_LINK, SET_RIGHTS_LIST, SET_SELECT_AT, SET_SELECT_FOND } from '../constants';
import { addDefaultRights, editDefaultRights, fetchDefaultRightsById } from '@/api/right';

const initialState = {
  // 当前选中的项目
  selectUnit: {},
  selectFond: {},
  selectAT: {},
  // 默认权限列表
  rightsList: [],
  // 导航详情表单ref
  formLink: {}
};

const UseRightContext = createContext();

const UseRightContextProvider = (props) => {
  const [state, dispatch] = useReducer(UseRightReducer, initialState);

  const actions = {
    /**
     * @description: 打开新增全宗弹窗
     */
    setSelectFond(data) {
      dispatch({ type: SET_SELECT_FOND, data });
    },

    /**
     * @description: 设置选中的档案类型
     */
    setSelectAT(data) {
      dispatch({ type: SET_SELECT_AT, data });
    },

    getRightsList(id) {
      fetchDefaultRightsById(id).then((res) => {
        const list = res.data;
        dispatch({ type: SET_RIGHTS_LIST, list });
      });
    },

    /**
     * @description: 保存表单form
     * @param {*} form 表单form
     * @return {*}
     */
    saveFormLink(form) {
      dispatch({ type: SAVE_FORM_LINK, data: form });
    },

    /**
     * @description: 触发导航信息表单提交
     */
    clickSaveBtn() {
      state.formLink?.submit();
    },

    /**
     * @description: 触发导航信息表单提交
     */
    saveRights(params) {
      if (params.id) {
        editDefaultRights(params).then((res) => {
          const list = [res.data];
          dispatch({ type: SET_RIGHTS_LIST, list });
          message.success('保存成功');
        });
      } else {
        addDefaultRights(params).then((res) => {
          const list = [res.data];
          dispatch({ type: SET_RIGHTS_LIST, list });
          message.success('保存成功');
        });
      }
    }
  };

  // watch选中的单位来加载全宗
  useEffect(() => {}, []);

  return (
    <UseRightContext.Provider value={{ ...state, ...actions }}>
      {props.children}
    </UseRightContext.Provider>
  );
};

export const useUseRightContext = () => {
  return useContext(UseRightContext);
};

export { UseRightContext, UseRightContextProvider };
